<?php
/**
 * Created by PhpStorm
 * User: hon(陈烁临) qq: 2275604210
 * Date: 2022/1/11
 * Time: 3:39 下午
 */

namespace App\Services;


use App\Models\Product;
use Illuminate\Support\Facades\DB;

class ProductService
{
    public  function add( array $params) :Product
    {
        $product = DB::transaction(function () use ($params){
            $product  = Product::create(['name'=> data_get($params,'name') ]);
            $skuData = data_get($params,'sku_data');
            $attrData = data_get($params,'att_data');
            //$attrData= [
            //  {
            //    "name": "颜色",
            //    "item": [
            //      "黑",
            //      "金",
            //      "白"
            //    ]
            //  },
            //  {
            //    "name": "内存",
            //    "item": [
            //      "16G",
            //      "32G"
            //    ]
            //  }
            //]
            if(!!$attrData != !!$skuData){
                throw new \InvalidArgumentException('属性数据和sku数据不合法');
            }
            $attrMArr = [];
            if($attrData){
                //添加属性
                foreach ($attrData as $attrDatum){

                    $option = $attrDatum['name'];
                    $values = $attrDatum['item'];
                    $attrMArr[] = $product->addAttrValues($option, $values);
                }
            }
            //[
            //  {
            //    "sku": "黑;16G",
            //    "amount": 80,
            //    "stock": 100
            //  },
            //]
            if($skuData){
                foreach ($skuData as $datum){
                    $skuAttr = is_array($datum['sku']) ? $datum['sku'] : explode(';',$datum['sku']);
                    $attr = [];
                    foreach ($skuAttr as $k => $v){
                        $attr[] = $attrMArr[$k]->firstWhere('value',$v);
                    }
                    $product->syncSkuWithAttrs($attr,['amount' => $datum['amount'], 'stock' => $datum['stock']]);
                }
            }
            return $product;
        });
        return  $product->load('skus.attrs.option');
    }

    public function getSkus($id)
    {
        $product = Product::where('id',$id)->first();
        return $product->load('skus.attrs');
    }
}
